package days38.title2;


import org.w3c.dom.Node;

/**
 * Definition for singly-linked list.
 * public class ListNode {
 * int val;
 * ListNode next;
 * ListNode() {}
 * ListNode(int val) { this.val = val; }
 * ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode newL1 = l1;
        ListNode newL2 = l2;
        int add = 0;
        ListNode addL1AndL2 = new ListNode();
        while (newL1 != null && newL2 != null) {
            ListNode tmpNode = new ListNode();
            int sum = newL1.val + newL2.val + add;
            if (sum >= 10) {
                add = 1;
                sum = sum % 10;
            } else
                add = 0;
            tmpNode.val = sum;
            tmpNode.next = addL1AndL2.next;
            addL1AndL2.next = tmpNode;
            newL1 = newL1.next;
            newL2 = newL2.next;
        }
        while (newL2 != null) {
            ListNode tmpNode = new ListNode();
            int sum = newL2.val + add;
            if (sum >= 10) {
                add = 1;
                sum = sum % 10;
            } else
                add = 0;
            tmpNode.val = sum;
            tmpNode.next = addL1AndL2.next;
            addL1AndL2.next = tmpNode;
            newL2 = newL2.next;
        }
        while (newL1 != null) {
            ListNode tmpNode = new ListNode();
            int sum = newL1.val + add;
            if (sum >= 10) {
                add = 1;
                sum = sum % 10;
            } else
                add = 0;
            tmpNode.val = sum;
            tmpNode.next = addL1AndL2.next;
            addL1AndL2.next = tmpNode;
            newL1 = newL1.next;
        }
        if (add != 0) {
            ListNode tmpNode = new ListNode();
            tmpNode.val = add;
            tmpNode.next = addL1AndL2.next;
            addL1AndL2.next = tmpNode;
        }
        return reverse(addL1AndL2.next);
    }

    private ListNode reverse(ListNode head) {
        if (head == null)
            return null;
        if (head.next == null)
            return head;
        ListNode tmpNode = new ListNode();
        tmpNode.next = head;
        head = head.next;
        tmpNode.next.next = null;
        while (head != null) {
            ListNode node = head;
            head = head.next;
            node.next = tmpNode.next;
            tmpNode.next = node;
        }
        return tmpNode.next;
    }
}